
package code.codeworld.common.res.controller;


import code.codeworld.common.res.model.Res;
import code.codeworld.common.res.model.vo.ResVo;
import code.codeworld.common.res.service.ResService;
import code.codeworld.common.kits.Request;
import code.codeworld.common.kits.Result;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import jakarta.validation.constraints.NotEmpty;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.math.BigInteger;
import java.util.List;

/**
 * world控制器
 *
 * @author freecode
 * @date 2023/03/23 00:20
 */
@CrossOrigin
@RequestMapping(Request.CODEWORLD_WEB)
@RestController
@Validated
public class ResCtl {
    @Resource
    private ResService ResService;

    /**
     * 添加Res
     *
     * @author freecode
     * @date 2023/03/23 00:20
     */
    @CrossOrigin
    @PostMapping("/res/add")
    public Result<String> add(@RequestBody @Valid Res res) {
        ResService.add(res);
        return Result.ok();
    }

    /**
     * 获取Res分页
     *
     * @author freecode
     * @date 2023/03/23 00:20
     */
    @CrossOrigin
    @GetMapping("/res/page")
    public Page<Res> page(ResVo resVo) {
        Integer pageSize = resVo.getPageSize();
        Integer pageNum = resVo.getPageNum();
        if (pageSize == null) {
            pageSize = BigInteger.TEN.intValue();
        }
        if (pageNum == null || pageNum <= BigInteger.ONE.intValue()) {
            pageNum = BigInteger.ZERO.intValue();
        } else {
            pageNum = pageNum - BigInteger.ONE.intValue();
        }
        resVo.setPageable(PageRequest.of(pageNum, pageSize));
        return ResService.page(resVo);
    }

    /**
     * 获取Res详情
     *
     * @author freecode
     * @date 2023/03/23 00:20
     */
    @CrossOrigin
    @GetMapping("/res/detail")
    public Result<Res> detail(@Valid Res res) {
        return Result.data(ResService.detail(res));
    }

    /**
     * 编辑Res
     *
     * @author freecode
     * @date 2023/03/23 00:20
     */
    @CrossOrigin
    @PostMapping("/res/edit")
    public Result<String> edit(@RequestBody @Valid Res res) {
        if (res.getId() == null) {
            return Result.paramError();
        }
        ResService.edit(res);
        return Result.ok();
    }

    /**
     * 删除Res
     *
     * @author freecode
     * @date 2023/03/23 00:20
     */
    @PostMapping("/res/delete")
    public Result<String> delete(@RequestBody @Valid @NotEmpty(message = "集合不能为空")
                                         List<Res> resList) {
        ResService.delete(resList);
        return Result.ok();
    }

}
